//
//  Comments.m
//  Truffle
//
//  Created by Averbouch David on 05/03/10.
//  Copyright 2010 Averbouch. All rights reserved.
//

#import "Comments.h"
#import "CommentsAdd.h"
#import "Commentaires.h"
#import "RestConnection.h"
#import "XMLParser.h"
#import "Service.h"
#import "DatasTruffle.h"
#import "DAOTruffle.h"
#import "Gateway.h"

@implementation Comments
@synthesize service, titre, commentaire, entete, contenu, listcom, maScrollView, assignedService, indexPass, controls;

- (void)viewDidLoad {
    [super viewDidLoad];
	self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];

	self.title = @"Commentaires";	
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
											  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
											  target:self action:@selector(addComment:)];
	
	controls = [[NSMutableArray alloc] init];
}

- (void) viewWillAppear:(BOOL)animated
{
	for (NSObject *control in controls) {
		[(UIView *)control removeFromSuperview];
		//[controls removeObject:control];
	}
	
	[[self view] setClearsContextBeforeDrawing:TRUE];
	positionFrame = 15;
	NSString *urlString = [NSString stringWithFormat:@"/iphone/listcomments/%@", [assignedService serviceid]];
	if(restConnection == nil) {
		restConnection = [RestConnection new];
		restConnection.baseURLString = [[[DatasTruffle getGateways] objectAtIndex:indexPass] ip];
		restConnection.delegate = self;
	}
	[restConnection performRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
	[[self view] setNeedsDisplay];
}

- (NSString *) chgBreakLine:(NSString *)text{
	
	NSString *result = @"";
	char a;	
	for (int i = 0; i < [text length]; i++) {
		a = [text characterAtIndex:i];
		
		if (a == '\\'){
			if ([text characterAtIndex:i+1] =='n'){
				result = [NSString stringWithFormat:@"%@\n",result];
				i=i+1;
				continue;
			}
		}
		
		result = [NSString stringWithFormat:@"%@%@", result, [[[NSString alloc] initWithBytes:&a length:1 encoding:NSASCIIStringEncoding] autorelease]];
	}
	return result;

}

- (void) writeComments{
	/*
	NSInteger ht = 15;
	NSInteger hc = 20;
	*/
	/* Mise en place de bulle similaire au sms */
	NSInteger ht = 13;
	NSInteger hc = 20;	
	UIImage* balloon = [[UIImage imageNamed:@"Balloon.png"] stretchableImageWithLeftCapWidth:15  topCapHeight:15];
	UIButton *zonetxt = [UIButton buttonWithType:UIButtonTypeCustom];
	
	//UIButton *zonetxt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	zonetxt.backgroundColor = [UIColor clearColor];
	zonetxt.enabled = FALSE;	
		
	hc *= [self countLines:contenu];
	commentaire = [[UILabel alloc] initWithFrame:(CGRectMake(10, 8, 280, hc))];
	commentaire.font = [UIFont fontWithName:@"Helvetica" size:16];
	//commentaire.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
	commentaire.backgroundColor = [UIColor clearColor];
	commentaire.textAlignment = UITextAlignmentLeft;
	commentaire.textColor = [UIColor blackColor];
	//commentaire.textColor = [UIColor whiteColor];
	//commentaire.shadowColor = [UIColor grayColor];
	commentaire.text = contenu;
	[commentaire setNumberOfLines:0];
	[commentaire setLineBreakMode:UILineBreakModeWordWrap];
	
	
	NSInteger h = positionFrame;
	NSInteger p = hc + 20;	
	
	
	titre = [[UILabel alloc] initWithFrame:(CGRectMake(10, p + 3, 290, ht))];
	titre.font = [UIFont fontWithName:@"Helvetica" size:11];
	titre.backgroundColor = [UIColor clearColor];
	titre.textAlignment = UITextAlignmentRight;
	titre.textColor = [UIColor grayColor];
	titre.text = entete;
	
	
	//NSInteger p = ht + hc + 10;
	zonetxt.frame = CGRectMake(10, h, 300, p);
	//positionFrame += p + 15;
	
	positionFrame += p + 25;
	[zonetxt setBackgroundImage:balloon forState:UIControlStateDisabled];

	//[zonetxt setAlpha:0.9f];
	
	[zonetxt addSubview:titre];
	[zonetxt addSubview:commentaire];
	
	[controls addObject:zonetxt];
	
	[titre release];
	[commentaire release];	
	[maScrollView addSubview:zonetxt];	

}

- (NSInteger) countLines:(NSString *)elem {
	NSInteger i = 0;
	NSInteger lines = 1;
	NSInteger nbchar = 0;

	for (i=0; i<[elem length]; i++) {
		nbchar ++;
		if (nbchar == 35 || [elem characterAtIndex:i] == '\n') {
			lines++;
			nbchar = 0;
		}
	}

	return lines;
}	
	
- (void) addComment:(id)sender {
	
	if(commentADD == nil)
		commentADD = [[CommentsAdd alloc] initWithNibName:@"CommentsAdd" bundle:nil];
	
	UINavigationController * addNavigationController = [[UINavigationController alloc] initWithRootViewController:commentADD];
	commentADD.idServ = [self.assignedService serviceid];
	commentADD.ipServ = restConnection.baseURLString;
	
	[self.navigationController presentModalViewController:addNavigationController animated:YES];
}

- (void)willSendRequest:(NSURLRequest *)request
{
	NSLog(@"Comments ---- Debut de la requete");
	[activityIndicator startAnimating];
}

- (void)didReceiveResponse:(NSURLResponse *)response
{
	NSLog(@"Comments ---- Did Receive Response");
}

- (void)finishedReceivingData:(NSData *)data callback:(NSString*)restconn
{	
	NSDictionary *rawData = [restConnection dictionaryData];
	listcom = [[rawData objectForKey:@"listcomment"] retain];
	NSLog(@"Comments ---- nb elements recus : %d", [listcom count]);
	NSInteger scrollPos = 0;
	//NSInteger oldscrollPos = 0;		// pour voir les deux derniers messages en tete de la page, decommenter les 2 lignes du for
	
	if ([listcom count] == 0){ 
		entete = assignedService.servicename; 
		contenu = @"Aucun commentaire";
		[self writeComments];
	}
	
	for(int i = 0; i < [listcom count]; i++) {
		//scrollPos = oldscrollPos;
		//oldscrollPos = positionFrame-15;

		NSLog(@"Comments ---- Timestamp : %@", [[listcom objectAtIndex:i] objectForKey:@"date"]);
		//1268927531861
		//NSString *d = [[listcom objectAtIndex:i] objectForKey:@"date"];		// pour la reception apres formatage de l equipe 2

		NSString *secondsString = [[listcom objectAtIndex:i] objectForKey:@"date"];

		// On enlève les millisecondes.
		secondsString = [secondsString substringToIndex:([secondsString length] - 3)];

		NSTimeInterval timeInterval = [secondsString doubleValue];
		NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
		NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
		[formatter setDateFormat:@"'le' MM/dd/yy 'à' HH:mm"];
		NSString *formattedDate = [formatter stringFromDate:date];
		
		entete = [NSString stringWithFormat:@"Posté par %@ %@", [[listcom objectAtIndex:i] objectForKey:@"pseudo"], formattedDate];		
		contenu = [[listcom objectAtIndex:i] objectForKey:@"content"];
		contenu = [self chgBreakLine:contenu];
		NSLog(@"Comments ---- Element : %@", contenu);
		[self writeComments];
	}
	[listcom release];
	[maScrollView setContentSize:(CGSizeMake(320, positionFrame+10))];
	
	// a commenter si vous voulez voir les 2 derniers messages en tete de page !!!
	if (positionFrame > 360) {
		scrollPos = positionFrame - 360;
	}

	[maScrollView setContentOffset:CGPointMake(0, scrollPos) animated:YES];

	[activityIndicator setHidesWhenStopped:TRUE];
	[activityIndicator stopAnimating];
	
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];	
}

- (void)viewDidUnload {}

- (void)dealloc {
    [super dealloc];
	[titre release];
	[commentaire release];
}


@end
